package phone.qyg.com.qyg.activity;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.ApplicationConfig;
import com.app.utils.JSONTool;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.view.SonicSessionClientImpl;
import com.tencent.sonic.sdk.SonicSession;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;

/**
 * 作者：lblbh on 2018/3/13 16:34
 * 邮箱：lanbuhan@163.com
 * 功能：超市列表
 */
@ContentView(R.layout.super_market_act)
public class SupermarketActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.web_view)
    WebView web_view;

    SonicSession sonicSession;

    SonicSessionClientImpl sonicSessionClient;

    String url = ApplicationConfig.SUPER_INDEX;

    @Override
    public void initData(Bundle savedInstanceState) {
        initWebView();
    }

    private void initWebView() {

        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
//        if (!SonicEngine.isGetInstanceAllowed()) {
//            SonicEngine.createInstance(new SonicRuntimeImpl(this), new SonicConfig.Builder().build());
//        }
//
//        // step 2: Create SonicSession
//        sonicSession = SonicEngine.getInstance().createSession(url, new SonicSessionConfig.Builder().build());
//        if (null != sonicSession) {
//            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
//        } else {
//            throw new UnknownError("create session fail!");
//        }

        //初始化布局
        WebSettings settings = web_view.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(false);// 允许放大缩小
        settings.setBuiltInZoomControls(false);// 显示放大缩小按钮
        settings.setDisplayZoomControls(false);// api 11以上
        settings.setSupportMultipleWindows(true);
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setTextZoom(100);
        web_view.setHorizontalScrollBarEnabled(false);
//        web_view.setBackgroundColor(Color.TRANSPARENT); // 设置背景色


        //如果不设置WebViewClient，请求会跳转系统浏览器
        web_view.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                SystemPrintl.systemPrintl("我加载的url--->>>"+url);
                view.loadUrl(url);
                return true;
            }

            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    SystemPrintl.systemPrintl("我加载的url-1111-->>>"+request.getUrl().toString());
                    view.loadUrl(request.getUrl().toString());
                    return true;
                }

                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //网页页面加载完毕
                if (sonicSession != null) {
                    SystemPrintl.systemPrintl("我加载的url-2222-->>>"+url);
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            //下面的方法是Tencent - sonic
            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    //step 6: Call sessionClient.requestResource when host allow the application
                    // to return the local data .
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }

        });


        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(web_view);
            sonicSessionClient.clientReady();
        } else { // default mode
            web_view.loadUrl(url);
        }
        web_view.addJavascriptInterface(this, "MyJSPhone");

        isUpdateUrl();
    }

    private void isUpdateUrl(){
        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ApplicationConfig.CULTURE_QX_URL);
        BroadcastReceiver mItemViewListClickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
//                intent.putExtra(TransformController.ChangeKEY.INTENT_KEY,result);
                String url = intent.getStringExtra(TransformController.ChangeKEY.INTENT_KEY);
                if(isRequestStr(url)){
                    SystemPrintl.systemPrintl("传递回来的url--->>"+url);
                    web_view.loadUrl(url);
//                    sonicSession = SonicEngine.getInstance().createSession(url, new SonicSessionConfig.Builder().build());
                }
            }
        };
        broadcastManager.registerReceiver(mItemViewListClickReceiver, intentFilter);
    }


    /**
     * MyJSPhone.testWithParam
     */

    @JavascriptInterface
    public void testWithParam(String result) {

        //{"subId":8,"title":"市民文化"}
        if(result.contains("subId") && result.contains("title") ){
            int subID = JSONTool.requestJSONfindNameCount(result,null,JSONTool.Enum.SUB_ID);
            String title = JSONTool.requestJSONfindName(result,JSONTool.Enum.TITLE);
            //int type,int id,String title
            Base base = new Base(1,subID,title);
            TransformController.transformControllerModel(QXApplication.getContext(), CultureListActivity.class,base);
        }
        SystemPrintl.systemPrintl("我点击获取到的url--->>>" + result);

    }

    /**
     *
     MyJSPhone.resourceClassify();
     */
    @JavascriptInterface
    public void resourceClassify() {
        TransformController.transformController(QXApplication.getContext(), CultureTypeActivity.class);
        SystemPrintl.systemPrintl("我在点击切换界面");
    }


    /**
     * 主要是把webview所持用的资源销毁，
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != web_view) {
            web_view.setWebChromeClient(null);
            web_view.setWebViewClient(null);
            web_view.destroy();
            web_view = null;
        }

        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
    }

    @Event(value = {R.id.back})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
        }
    }


    @Override
    public void initSucessView() {}
    @Override
    public void initViewHandler() {}
}
